<template>
    <div>
        <el-page-header @back="goBack" :content="pageTitle"></el-page-header>
        <div class="common_line"></div>
        <el-form ref="addForm" :model="addForm" :rules="rules" label-width="auto" style="margin-top: 20px;width: 85%;">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="收支类型:" prop="record_type">
                        <el-radio-group v-model="addForm.record_type" @change="typeChange">
                            <el-radio :label="2">支出</el-radio>
                            <el-radio :label="1">收入</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="分类:" prop="category">
                        <div style="display: flex;align-items: center;gap: 20px;">
                            <el-select style="width: 240px;" v-model="addForm.category" placeholder="请选择" 
                                @change="cateChange" clearable>
                                <el-option v-for="item in cateLists" :key="'cate_'+item.id" 
                                    :label="item.name" :value="item.id"></el-option>
                            </el-select>
                            <span @click="showAddCateAlert=true" style="cursor: pointer;font-size: 13px;color: #0099ff;">新增分类</span>
                        </div>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="金额:" prop="paid_fee">
                        <el-input style="width: 240px" v-model="addForm.paid_fee" placeholder="请输入" maxlength="20" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="showSalary">
                    <el-form-item label="员工姓名:" prop="staff_user">
                        <div class="choose_border" @click="chooseUsers('staff')">
                            <span style="color: #c0c4cf;" v-if="!staff_name">请选择</span>
                            <span>{{ staff_name }}</span>
                            <!-- <i class="el-icon-circle-close icon" @click.stop="clearValue('staff')"></i> -->
                        </div>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="日期:" prop="expenditure_date">
                        <el-date-picker v-model="addForm.expenditure_date" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                            style="width: 240px" placeholder="请选择日期" clearable>
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="!showSalary">
                    <el-form-item label="往来单位:">
                        <div v-if="partnerName" class="set_user_done" @click="choosePartner">{{ partnerName }}</div>
                        <div v-else class="set_user_none" @click="choosePartner">请选择往来单位</div>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="账户:" prop="pay_type">
                        <el-select style="width: 240px;" v-model="addForm.pay_type" placeholder="请选择" clearable>
                            <el-option v-for="item in payTypes" :key="'pay_'+item.value" 
                                :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="isAdmin">
                    <el-form-item label="经办人:">
                        <div class="choose_border" @click="chooseUsers('handler')">
                            <span style="color: #c0c4cf;" v-if="!handler_name">请选择</span>
                            <span>{{ handler_name }}</span>
                            <!-- <i class="el-icon-circle-close icon" @click.stop="clearValue('handler')"></i> -->
                        </div>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-else>
                    <el-form-item label="经办人:">
                        <div>{{ handler_name }}</div>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="20">
                    <el-form-item label="备注:">
                        <el-input maxlength="200" show-word-limit type="textarea" :autosize="{ minRows: 2, maxRows: 6 }" v-model="addForm.remark" placeholder="请输入" clearable />
                    </el-form-item>
                </el-col>
            </el-row>

            <div style="font-size: 14px;font-weight: bold;height: 48px;line-height: 48px;margin-top: 10px;">上传附件</div>
            <el-row>
                <el-upload multiple ref="fileUpload" action="anything" :file-list="fileUploadList"
                    :http-request="(params) => uploadSectionFile(params)" :limit="5"
                    :on-preview="previewClick" :on-remove="(file) => removeFile(file)">
                    <el-button size="small" :disabled="canUpload" :class="canUpload?'btn_info_color':'btn_primary_color'" 
                        style="margin: 10px 0 0 40px;" icon="el-icon-upload2">上传附件</el-button>
                    <div slot="tip" class="el-upload__tip" style="margin-left: 20px;white-space:nowrap;display: inline-block;">
                        最多上传5个附件，单个附件大小限制在{{ max_file_size }}MB之内
                    </div>
                </el-upload>
            </el-row>
        </el-form>

        <bottom-btns
            Width="70%"
            MarginTop="30px"
            :buttons="buttonList"
            @superBtnClick="handleButtonClick"
        ></bottom-btns>

        <!-- 选择往来单位 -->
        <el-dialog title="往来单位" :visible.sync="showPartner" :close-on-click-modal="false" width="40%" center append-to-body>
            <div class="partner_view">
                <el-tabs v-model="activeName" @tab-click="tabClick">
                    <el-tab-pane label="客户" name="customer">
                        <div class="lists">
                            <div class="cell" v-for="item in customerList" :key="'cus_'+item.id" @click="cellClick(item, 'customer')">
                                <span :style="{color: item.selected?'#068cee':'#333'}">{{ item.name }}</span>
                                <i v-if="item.selected" class="el-icon-check icon"></i>
                            </div>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="供货商" name="supplier">
                        <div class="lists">
                            <div class="cell" v-for="item in supplierList" :key="'sup_'+item.id" @click="cellClick(item, 'supplier')">
                                <span :style="{color: item.selected?'#068cee':'#333'}">{{ item.name }}</span>
                                <i v-if="item.selected" class="el-icon-check icon"></i>
                            </div>
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </div>
            <!-- <span slot="footer" class="dialog-footer">
                <el-button @click="showPartner=false">关 闭</el-button>
            </span> -->
        </el-dialog>

        <!-- 新增分类 -->
        <el-dialog
            title="新增费用类型"
            :visible.sync="showAddCateAlert"
            width="30%"
            :close-on-click-modal="false"
            append-to-body
            center>
            <div style="padding-left: 20px;">
                <el-form :model="cateInfo" label-width="auto" ref="cateForm" :rules="cateRules">
                    <el-form-item label="费用类型:" prop="name">
                        <el-input style="width: 240px;" maxlength="100" v-model="cateInfo.name" placeholder="请输入" clearable />
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="showAddCateAlert=false">取 消</el-button>
                <el-button size="small" class="btn_primary_color" @click="addCategory">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 选择经办人 -->
        <choose-user
            :showChooseUser="showChooseUserAlert"
            :selectUsers="selectedUsers.users"
            :title="selectedUsers.title"
            @chooseOK="chooseUserOK"
            @hidden="showChooseUserAlert=false"
        ></choose-user>
    </div>
</template>

<script>
import { getUserList } from "@/api/user";
import { getCustomerList, getSupplierList } from "@/api/cooperate";
import { addExpend, editExpend, infoExpend, listExpendCategory, addExpendCategory } from "@/api/expenses";
import bottomBtns from "@/components/bottomBtns";
import chooseUser from "@/components/chooseUser";
import { baseUrl } from '@/config/env'
import { getToken } from '@/utils/auth'
const moment = require('moment')

export default {
    name: 'expenseEdit',
    components: {
        bottomBtns,
        chooseUser
    },
    data() {
        return {
            showLoading: false,
            showAddCateAlert: false,
            showChooseUserAlert: false,
            backShouldRefresh: false,  //返回是否刷新分类
            userType: '',
            showSalary: false,
            isAdmin: false,
            showPartner: false,
            canUpload: false,
            activeName: 'customer',
            expendId: '',
            pageTitle: '',
            addForm: {
				corp: '',
                category: '',
                pay_type: 2,
                record_type: 2,
                customer: '',
                expenditure_date: '',
                handler_user: '',
                paid_fee: '',
                remark: '',
                suppliers: '',
                file_id_list: [],
                staff_user: ''
            },
            rules:{
                record_type: [
                    { required: true, message: "请选择收支类型", trigger: "change" },
                ],
                category: [
                    { required: true, message: "请选择费用类型", trigger: "change" },
                ],
                paid_fee: [
                    { required: true, message: "请输入金额", trigger: "blur" },
                ],
                expenditure_date: [
                    { required: true, message: "请选择日期", trigger: "change" },
                ],
                pay_type: [
                    { required: true, message: "请选择账户", trigger: "change" },
                ]
            },
            cateInfo: {
                name: '',
                record_type: 2,
            },
            cateRules:{
                name: [
                    { required: true, message: "请输入费用类型", trigger: "blur" },
                ],
            },
            partnerName: '',
            handler_name: '',
            staff_name: '',
            handlersList: [],
            cateLists: [],
            staffList: [],
            customerList: [],
            supplierList: [],
            payTypes: [
                {label: '微信', value: 2},
				{label: '支付宝', value: 5},
				{label: '现金', value: 1},
				{label: '银行转账', value: 3},
				{label: '其他', value: 4}
            ],
            buttonList: [
                { name: '保存', type: 'commit', id:'1' },
                { name: '取消', type: 'cancel', id:'2' }
            ],
            fileUploadList: [],
            max_file_size: 10,  //最大可上传文件大小（MB）
        }
    },
    props: {
        corpId: {
            type: Number
        },
        editId: {
            type: Number
        }
    },
    computed: {
        selectedUsers() {
            let users = [], title = '';
            if (this.userType == 'staff'){
                if (this.addForm.staff_user){
                    users = [{id: this.addForm.staff_user}]
                }
                title = '选择员工'
            }else if (this.userType == 'handler'){
                if (this.addForm.handler_user){
                    users = [{id: this.addForm.handler_user}]
                }
                title = '选择经办人'
            }
            return {
                users, title
            }
        }
    },
    mounted() {
        this.addForm.corp = this.corpId
        this.isAdmin = this.$store.state.isAdmin
        this.expendId = this.editId
        this.handler_name = this.$store.state.userInfo.username
        this.addForm.handler_user = this.$store.state.userInfo.id
        this.addForm.expenditure_date = moment().format('yyyy-MM-DD')

        this.getCategorys()
        this.getCustomers()
        if (this.expendId) {
            this.pageTitle = '编辑日常收支'
            this.getInfo()
        }else{
            this.pageTitle = '新增日常收支'
        }
    },
    methods: {
        goBack() {
            this.$emit('hidden', {isRefresh: this.backShouldRefresh})
        },
        chooseUsers(type) {
            this.userType = type
            this.showChooseUserAlert = true
        },
        clearValue(type) {
            if (type == 'staff'){
                this.addForm.staff_user = ''
                this.staff_name = ''
            }else if (type == 'handler'){
                this.addForm.handler_user = ''
                this.handler_name = ''
            }
        },
        chooseUserOK(res) {
            if (this.userType == 'staff'){
                this.addForm.staff_user = res.length ? res[0].id : ''
                this.staff_name = res.length ? res[0].username : ''
            }else if (this.userType == 'handler'){
                this.addForm.handler_user = res.length ? res[0].id : ''
                this.handler_name = res.length ? res[0].username : ''
            }
            this.showChooseUserAlert = false
        },
        getCategorys() {
            listExpendCategory({
                corp: this.addForm.corp,
                record_type: this.addForm.record_type,
                page: 1,
                num: 999
            }).then(res => {
                this.cateLists = res.data.data.category_list
            })
        },
        addCategory() {
            var that = this
            that.$refs['cateForm'].validate(valid => {
                if(!valid) return
                
                that.cateInfo.corp = that.addForm.corp
                that.cateInfo.record_type = that.addForm.record_type
                addExpendCategory(that.cateInfo).then(res => {
                    if (res.code == 200){
                        that.cateInfo.name = ''
                        that.getCategorys()
                        that.showAddCateAlert = false
                        that.backShouldRefresh = true
                        that.$message({
                            message: '新增成功',
                            type: 'success'
                        })
                    }
                })
            })
        },
        typeChange(val) {
            this.addForm.category = ''
            this.getCategorys()
        },
        choosePartner() {
            this.showPartner = true
        },
        cellClick(item, type) {
            if (type == 'customer') {
                this.customerList.forEach(_item => {
                    _item.selected = false
                    if (_item.id === item.id){
                        _item.selected = true
                        this.addForm.customer = item.id
                        this.addForm.suppliers = ''
                        this.partnerName = item.name
                        this.showPartner = false
                    }
                })
            }else {
                this.supplierList.forEach(_item => {
                    _item.selected = false
                    if (_item.id === item.id){
                        _item.selected = true
                        this.addForm.suppliers = item.id
                        this.addForm.customer = ''
                        this.partnerName = item.name
                        this.showPartner = false
                    }
                })
            }
        },
        tabClick(val) {
            if (val.name == 'customer'){
                this.getCustomers()
            }else {
                this.getSuppliers()
            }
        },
        getCustomers() {
            let params = {
                corp: this.addForm.corp,
                page: 1,
                num: 999
            }
            getCustomerList(params).then(res => {
                this.customerList = res.data.data.customer_list.filter(item => {
                    item.selected = false
                    if (this.addForm.customer === item.id){
                        item.selected = true
                    }
                    return item
                })
            })
        },
        getSuppliers() {
            let params = {
                corp: this.addForm.corp,
                page: 1,
                num: 999
            }
            getSupplierList(params).then(res => {
                this.supplierList = res.data.data.supplier_list.filter(item => {
                    item.selected = false
                    if (this.addForm.suppliers === item.id){
                        item.selected = true
                    }
                    return item
                })
            })
        },
        cateChange(val) {
            let cateName = ''
            this.cateLists.forEach(item => {
                if (item.id === val){
                    cateName = item.name
                }
            })

            if (this.addForm.record_type===2 && cateName=='员工工资'){
                this.showSalary = true
            }else {
                this.showSalary = false
            }
        },
        getInfo() {
            infoExpend(this.expendId, {corp: this.addForm.corp}).then(res => {
                let info = res.data.data
                if (info.customer) {
                    this.partnerName = info.customer_detail.name
                }else if (info.suppliers) {
                    this.partnerName = info.suppliers_detail.name
                }else if (info.staff_user_detail) {
                    this.staffName = info.staff_user_detail.username
                }
                this.addForm = info
                this.getCategorys()
                // 附件
                if (info.file_list_show && info.file_list_show.length){
                    this.addForm.file_id_list = info.file_list_show.map(item => item.id)
                    this.fileUploadList = info.file_list_show.filter(item => {
                        item.url = item.url_show
                        item.name = item.file_name
                        return item
                    })
                }else{
                    this.addForm.file_id_list = []
                }
            })
        },
        handleButtonClick(item) {
            switch (item.id) {
                case '1':   // 保存
                    this.commit()
                    break;
                case '2':   // 取消
                    this.goBack()
                    break;
            
                default:
                    break;
            }
        },
        commit() {
            var that = this
            that.$refs['addForm'].validate(valid => {
                if(!valid) return
                
                let temp = null
                if (that.expendId) {
                    delete that.addForm['expenditure_type']
                    temp = editExpend(that.expendId, that.addForm)
                }else{
                    temp = addExpend(that.addForm)
                }

                temp.then(res => {
                    if (res.code == 200){
                        that.$message({
                            message: '操作成功',
                            type: 'success'
                        })
                        that.$emit('success')
                    }
                })
            })
        },
        // 选择员工
        staffChange(value) {
            let [ id, username ] = value.split('&&')
            this.addForm.staff_user = id
            this.staff_name = username
        },
        remoteMethodWithStaff(query) {
            if (query !== '') {
                this.showLoading = true
                getUserList({
                    corp: this.addForm.corp,
                    username: query
                }).then(res => {
                    this.showLoading = false
                    this.staffList = res.data.users.filter(item => {
                        item.label = item.username
                        item.value = item.id+'&&'+item.username
                        if (item.phone_no){
                            item.label += ('（'+item.phone_no+'）')
                        }
                        return item
                    });
                })
            } else {
                this.staffList = []
            }
        },
        // 选择经办人
        handlerPersonChange(value) {
            let [ id, username ] = value.split('&&')
            this.addForm.handler_user = id
            this.handler_name = username
        },
        remoteMethodWithHandler(query) {
            if (query !== '') {
                this.showLoading = true
                getUserList({
                    corp: this.addForm.corp,
                    username: query
                }).then(res => {
                    this.showLoading = false
                    this.handlersList = res.data.users.filter(item => {
                        item.label = item.username
                        item.value = item.id+'&&'+item.username
                        if (item.phone_no){
                            item.label += ('（'+item.phone_no+'）')
                        }
                        return item
                    });
                })
            } else {
                this.handlersList = []
            }
        },
        // ===================== 附件上传相关 ===========================
        // 上传前校验
        beforeUpload (file) {
            let isRightSize = file.size / 1024 / 1024 < this.max_file_size
            if (!isRightSize) {
                this.$message.error('文件大小超过' + this.max_file_size + 'MB')
            }
            // let fileArr = file.name.split('.')
            // let isAccept = new RegExp(this[uploadType].accept.join('|')).test('.' + fileArr[fileArr.length - 1])
            // if (!isAccept) {
            //     this.$message.error('请上传' + this[uploadType].accept.join(',') + '类型的文件')
            // }
            return isRightSize
        },
        // 自定义附件上传
        uploadSectionFile (params) {
            let _this = this
            if (!this.beforeUpload(params.file)) {
                params.onError()
                return
            }
            if (this.canUpload) return
             const loading = this.$loading({
                lock: true,
                text: '正在上传附件中，请稍后...'
            });
            _this.canUpload = true
            const formdata = new FormData()
            formdata.append('up_file', params.file)
            formdata.append('file_name', params.file.name)
            var xhr = new XMLHttpRequest();
            xhr.open("POST", baseUrl+'/upload_file/ali_oss_priv', true); //链接改成你项目中的
            xhr.setRequestHeader("TOKEN", getToken());  //令牌改成你项目中的
            xhr.setRequestHeader("CORP-ID", this.addForm.corp);  //令牌改成你项目中的
            xhr.send(formdata);
            xhr.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    var obj = JSON.parse(xhr.responseText); //返回值
                    _this.addForm.file_id_list.push(obj.data.id)
                    _this.fileUploadList.push({
                        name: obj.data.file_name,
                        url: obj.data.url_show,
                        id: obj.data.id
                    })
                    _this.$message.success('上传成功')
                    _this.canUpload = false
                    loading.close();
                }
            }
        },
        previewClick(file) {
            location.href = file.url
        },
        removeFile(file) {
            this.fileUploadList = this.fileUploadList.filter(item => item.id !== file.id)
            this.addForm.file_id_list = this.addForm.file_id_list.filter(item => item !== file.id)
        }
    }
}
</script>

<style lang="less" scoped>
    @import '../../style/mixin.less';
    .set_user_done {
        margin-left: 10px;
        font-size: 14px;
        &:hover {
            color: @blue;
            cursor: pointer;
        }
    }
    .set_user_none {
        margin-left: 10px;
        font-size: 14px;
        color: @blue;
        &:hover {
            cursor: pointer;
        }
    }
    .partner_view {
        .lists {
            height: 300px;
            overflow-y: auto;
            .cell {
                display: flex;
                border-bottom: 1px solid #eee;
                height: 40px;
                align-items: center;
                justify-content: space-between;
                .icon {
                    color: @blue;
                    font-size: 18px;
                }
            }
        }
    }
</style>

<style>
.el-upload-list__item {
    margin-left: 36px !important;
    width: calc(100% - 36px) !important;
}
</style>